package cn.wyl.system.service.impl;

import cn.wyl.system.domain.Menu;
import cn.wyl.system.mapper.MenuMapper;
import cn.wyl.system.service.IMenuService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {
        List<Menu> menus= menuMapper.findAll();
        //将所有菜单查询出来 - 装到map集合 => 为了方便通过id找菜单对象
        HashMap<Long, Menu> map = new HashMap<>();
        for (Menu menu:menus){
            map.put(menu.getId(),menu);
        }
        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu:menus){
            if (menu.getParentId() == null){
                menuTree.add(menu);
            }else {
                Long parentId = menu.getParentId();
                Menu parentMenu = map.get(parentId);
                if (parentMenu != null){
                    //将自己状态父部门的children集合中
                    parentMenu.getChildren().add(menu);
                }
            }
        }
        return menuTree;
    }
}
